/*
 * @Description:
 * @Author: wsm
 * @Date: 2021-06-22 10:25:33
 * @LastEditTime: 2022-01-10 17:47:07
 * @LastEditors: Please set LastEditors
 * @Reference:
 */
import { Inject, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { cacheConf } from '@conf/cache.conf';
import { sysConf } from '@conf/sys.conf';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { MenuService, SettingsService } from '@delon/theme';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { BaseService } from '../core/base.service';
import { EACacheService } from '../core/cache.service';
import { EAEventService } from '../core/event.service';
@Injectable({
  providedIn: 'root'
})
export class EAUserService extends BaseService {
  /**
   * 账号密码登录
   */
  $api_login_by_account = `/api/mdc/cuc/user/login?_allow_anonymous=true`;
  /**
   * 手机号登录
   */
  $api_login_by_mobile = `/api/mdc/cuc/user/sms/login?_allow_anonymous=true`;
  // 登录路径
  private $api_login = `/scce/cuc/cuc/user/login?_allow_anonymous=true`;
  private $api_captcha_login = `/scce/cuc/cuc/user/sms/login?_allow_anonymous=true`;
  private $api_register: any = ``;
  // 获取协议信息
  public $api_get_agreement_info = `/scce/pbc/pbc/agreementInfo/getAgreementInfoByType?_allow_anonymous=true`;
  // 未登录验证身份
  public $forgetPasswordVerifyIdentity = `/api/mdc/cuc/userBasicInfo/forgetPassword/verifyIdentity?_allow_anonymous=true`;
  // 通过手机号发送短信验证码
  public $api_send_sms_by_mobile = `/api/mdc/pbc/smsSend/getSMVerificationCode?_allow_anonymous=true&_allow_badcode=true`;
  // 未设置密码的用户设置用户密码
  public $api_set_password = `/scce/cuc/cuc/userBasicInfo/setPassword`;
  // 凭证修改密码
  // 未登录账号发送验证码
  public $getAccountSMVerificationCode = `/api/mdc/cuc/userBasicInfo/forgetPassword/getAccountSMVerificationCode?_allow_anonymous=true`;
  // 凭证修改密码
  public $voucherUpdatePassword = `/api/mdc/cuc/userBasicInfo/forgetPassword/voucherUpdatePassword?_allow_anonymous=true`;
  // 检测用户名是否存在
  public $api_validate_username_exists = `/tms/cuc/cuc/userBasicInfo/checkUserName?_allow_badcode=true`;
  // 获取当前用户信息
  public $api_get_current_user = `/scce/cuc/cuc/user/getUserDetail`;
  // 校验手机号是否可注册
  private $api_vaild_register: any = ``;
  /**
   * 登出
   */
  $api_logout = `/scce/cuc/cuc/user/logout`;
  /**
   * 根据Token获取用户详情
   */
  $api_get_user_by_token = `/api/mdc/cuc/user/getUserDetail`;
  /**
   * 获取用户菜单
   */
  $api_get_user_menus = `/api/mdc/cuc/functionInfo/getUserHaveFunctionsList`;
  /**
   * 获取用户角色
   */
  $api_get_user_roles = `/scce/cuc/cuc/roleInfo/getMyRoleList`;
  // 获取一、二、三级地区详情
  public $api_getRegionToThree = `/scce/pbc/pbc/region/getRegionToThree?_allow_anonymous=true`;
  constructor(
    public injector: Injector,
    public cacheSrv: EACacheService,
    public eventSrv: EAEventService,
    public settings: SettingsService,
    private menuService: MenuService,
    public router: Router,
    @Inject(DA_SERVICE_TOKEN) public tokenSrv: ITokenService,
    private settingSrv: SettingsService
  ) {
    super(injector);
  }

  /**
   * 登录状态
   */
  public get loginStatus(): boolean {
    try {
      return !!this.tokenSrv.get()?.token;
    } catch (error) {
      return false;
    }
  }

  /**
   * @description 手机号登录
   * @param mobile 手机号
   * @param captcha 验证码
   */
  loginByMobile(mobile: string, captcha: string, sc: string) {
    this.tokenSrv.set({ token: 'sfdsfsdf'});
    this.doAfterLogin();
    this.router.navigate(['/']);
    // this.asyncRequest(this.$api_login_by_mobile, { phone: mobile, smsCode: captcha, sc }, 'POST', true, 'FORM').then(res => {
    //   if (res?.token) {
    //     // this.cacheSrv.set(cacheConf.token, res.token);
    //     this.tokenSrv.set({ token: res.token });
    //     this.doAfterLogin();
    //     this.router.navigate(['/']);
    //   }
    // });
  }

  /**
   * @description 账号密码登录
   * @param account 账号
   * @param password 密码
   */
  loginByAccount(account: string, password: string, sc?: string) {
    this.request(this.$api_login_by_account, { username: account, password, sc }, 'POST', true, 'FORM').subscribe((res: any) => {
      if (res?.token) {
        this.tokenSrv.set({ token: res.token });
        this.doAfterLogin();
        this.router.navigate(['/']);
      }
    });
  }

  async doAfterLogin() {
    await this.loadUserInfo();
    await this.loadUserMenus();
    this.loadApp();
  }

  /**
   * 加载用户信息
   */
  async loadUserInfo() {
    // return this.asyncRequest(this.$api_get_user_by_token).then(res => {
    //   this.cacheSrv.set(cacheConf.env, {
    //     appId: sysConf.appId,
    //     tenantId: res?.tenantId || sysConf.tenantId,
    //     enterpriseId: res?.enterpriseId || sysConf.enterpriseId
    //   });
    //   this.cacheSrv.set(cacheConf.user, res);
    //   this.settings.setUser(res);
    // });
    this.cacheSrv.set(cacheConf.env, {
      appId: sysConf.appId,
      tenantId:  sysConf.tenantId,
      enterpriseId: sysConf.enterpriseId
    });
    this.cacheSrv.set(cacheConf.user, 'sdfafdsfa');
    // this.settings.setUser('');
  }

  /**
   * 加载用户菜单
   */
  async loadUserMenus() {
    // return this.asyncRequest(this.$api_get_user_menus, {
    //   appId: this.envSrv.getEnvironment().appId
    // }).then(res => {
    //   this.cacheSrv.set(cacheConf.menu, res);
    //   this.menuService.add(res);
    // });
    this.request('assets/mocks/menu-data.json', {}, 'GET').subscribe((res: any) => {
      this.cacheSrv.set(cacheConf.menu, res.menu);
      this.menuService.add(res.menu);
    });
  }

  /**
   * 加载系统信息
   */
  loadApp() {
    this.http.get(`assets/mocks/app-data.json`).subscribe(res => {
      if (res.app) {
        this.settings.setApp(res.app);
      }
    });
  }

  /**
   * 登出
   */
  logout() {
    this.settingSrv.setApp({});
    this.tokenSrv.clear();
    this.cacheSrv.clear();
    this.router.navigate(['/']);
  }

  /**
   * 用户注册
   */
  register(params: any): Observable<boolean> {
    const obj: any = {};
    obj.appId = sysConf.appId;
    obj.masterAccount = 0;
    if (params.regType === 'account') {
      obj.account = params.account;
      obj.loginCipher = params.loginCipher;
      obj.type = 0;
    } else if (params.regType === 'phone') {
      obj.phone = params.phone;
      obj.smsVerificationCode = params.smsVerificationCode;
      obj.type = 1;
    }
    return this.http.post(this.$api_register, obj).pipe(
      map((res: any): any => {
        if (res.success === true) {
          return true;
        }
      })
    );
  }

  /**
   * 校验手机号是否可注册
   */
  checkPhoneHasRegister(params: any): Observable<boolean> {
    const formdata = new FormData();
    formdata.append('appId', sysConf.appId);
    formdata.append('phoneNumber', params);
    return this.http.post(this.$api_vaild_register, formdata).pipe(
      map((res: any): any => {
        if (res.success === true) {
          return true;
        }
      })
    );
  }
}
